package org.example.dao.impl;

import org.example.dao.DeptDao;
import org.example.entity.Dept;

import java.sql.Connection;
import java.util.List;

/**
 * 访问部门表的类，Dao表示数据访问对象
 */
public class DeptDaoImpl implements DeptDao {
    /**
     * 添加部门（带事务的方法）
     * @param dept 部门对象
     */
    public void addDept(Connection conn, Dept dept) {
        String sql = "INSERT INTO dept VALUES(NULL,?,?)";
        int row = DBUtil.executeSqlByTran(conn,sql,dept.getDeptName(),dept.getDeptLoc());
        if(row > 0) {
            System.out.println("添加成功");
        }
    }

    public void delDept(int deptId) {
        String sql = "DELETE FROM dept WHERE dept_id = ?";
        int row = DBUtil.executeSql(sql,deptId);
        if(row > 0) {
            System.out.println("删除成功");
        }
    }

    public void updDept(Dept dept) {
        String sql = "UPDATE dept SET dept_name = ?,dept_loc = ? WHERE dept_id = ?";
        int row = DBUtil.executeSql(sql,dept.getDeptName(),dept.getDeptLoc(),dept.getDeptId());
        if(row > 0) {
            System.out.println("更新成功");
        }
    }

    /**
     * 根据部门id查询部门
     * @param id
     * @return
     */
    public Dept getDeptById(int id) {
        // DeptMapper deptMapper = new DeptMapper();
        String sql = "select * from dept where dept_id = ?";
        return DBUtil.executeQuery(Dept::map,sql,id).get(0);
    }
    public Dept getDeptByName(String  name) {
        // DeptMapper deptMapper = new DeptMapper();
        String sql = "select * from dept where dept_name = ?";
        return DBUtil.executeQuery(Dept::map,sql,name).get(0);
    }

    public List<Dept> getAllDepts() {
        String sql = "select * from dept";
        return DBUtil.executeQuery(Dept::map,sql);
    }

    @Override
    public int queryDeptIdByName(String dept_name) {
        String sql = "SELECT * FROM dept WHERE dept_name=?";
        List<Dept> depts = DBUtil.executeQuery(Dept::map,sql,dept_name);
        if(depts.size() > 0) {
            return depts.get(0).getDeptId();
        }
        return 0;
    }

}
